﻿using System;
using System.Collections.Generic;
using System.IO;
using CSJ2K.Util.IO;

namespace CSJ2K.Jpc.Segments
{
    /// <summary>Tile-part lengths (TLM)</summary>
    /// <comment>
    /// Function: Describes the length of every tile-part in the codestream. Each tile-part's 
    ///      length is measured from the first byte of the SOT marker segment to the end of 
    ///      the bit-stream data of that tile-part. The value of each individual tile-part 
    ///      length in the TLM marker segment is the same as the value in the corresponding 
    ///      Psot in the SOT marker segment.
    /// Usage: Main header. Optional use in the main header only. There may be multiple TLM 
    ///      marker segments in the main header. 
    /// Length: Variable depending on the number of tile-parts in the codestream.
    /// </comment>
    public class TLM : Segment
    {
        /// <summary>Index of this marker segment relative to all other TLM marker segments present in the current header.</summary>
        public byte Z;
        /// <summary>Size of the Ttlm and Ptlm parameters</summary>
        public byte S;
        public class TilePartInfo
        {
            /// <summary>Tile index of the ith tile-part.</summary>
            public ushort T;

            /// <summary>Length, in bytes, from the beginning of the SOT marker of the ith tile-part to the end of the bit stream data for that tile-part.</summary>
            public ushort P;
        }
        /// <summary>Pairs of Ttlm and Ptlm for each tile-part in this marker segment.</summary>
        public TilePartInfo[] TilePart;

        public TLM(CodeStream codeStream, Stream source)
            : this(source, (Markers)StreamUtil.ReadBUInt16(source)) { }
        public TLM(Stream source, Markers marker)
            : base(source, marker, true)
        {
            if (marker != Markers.TLM) throw (new ApplicationException("Attempting to create segment of the wrong type."));

            // TODO: Deserialize MarkerSegment
            byte[] buffer = StreamUtil.ReadBytes(source, Length - 2);
        }
    }
}
